package com.gpay.erp.web.control;

import com.gpay.erp.core.system.bean.NoteType;
import com.gpay.erp.core.system.bean.PayType;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.services.common.GlobalStatus;
import com.gpay.erp.services.common.PaytypeService;
import com.gpay.erp.services.purchase.*;
import com.gpay.erp.services.purchase.bean.*;
import com.gpay.erp.web.util.Arith;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.PaidApplicationMode;
import com.gpay.erp.web.vo.PaymentOrderMode;
import com.gpay.erp.web.vo.ResponseInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by wuzonghui on 15/11/5.
 * 付款单控制controller
 */
@Controller
@RequestMapping("/paymentOrder/")
public class PaymentOrderController extends BaseController {
    private Log logger = LogFactory.getLog(ApplicationController.class);
    @Autowired
    private PaidApplicationService paidApplicationService;
    @Autowired
    private PaidApplicationSubService paidApplicationSubService;
    @Autowired
    private GlobalStatus globalStatus;
    @Autowired
    private ContractService contractService;
    @Autowired
    private MessageSource messageSource;
    @Autowired
    private PaytypeService paytypeService;
    @Autowired
    private PaymentOrderService paymentOrderService;
    @Autowired
    private PaymentOrderSubService paymentOrderSubService;


    // 页面跳转 付款列表
    @RequestMapping("payList")
    public String payList() {
        return "pay/payList";
    }

    // 页面跳转 付款单新增
    @RequestMapping("payAdd")
    public String payAdd(String id, ModelMap modelMap) {
        modelMap.addAttribute("payId", id);
        return "pay/payAdd";
    }

    // 页面跳转 付款单明细
    @RequestMapping("payDetail")
    public String payDetail(String id, ModelMap modelMap) {
        modelMap.addAttribute("payId", id);
        return "pay/payDetail";
    }

    /**
     * 查询支付方式
     *
     * @param request
     * @param response
     */
    @RequestMapping("paytype")
    public void paytype(HttpServletRequest request,
                        HttpServletResponse response) {
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setResult("00000");
        responseInfo.setMessage(messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA));
        PayType payType = new PayType();
        List<PayType> payTypes = paytypeService.selectListPayType();
        responseInfo.setObject(payTypes);
        WebUtil.responseToJson(response, responseInfo);

    }

    /**
     * 根据支付方式查询票据
     *
     * @param request
     * @param response
     */
    @RequestMapping("noteTypeByFid")
    public void noteTypeByFid(String f_paytypeId, HttpServletRequest request,
                              HttpServletResponse response) {
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setResult("00000");
        responseInfo.setMessage(messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA));
        List<NoteType> noteTypes = paytypeService.selectListByFid(f_paytypeId);
        responseInfo.setObject(noteTypes);
        WebUtil.responseToJson(response, responseInfo);

    }


    /**
     * 审核通过的状态点击 财务付款  财务拨款状态点击明细
     *
     * @param id       采购申请id
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPaymentOrderSub")
    public void selectPaymentOrderSub(String id,
                                      HttpServletRequest request, HttpServletResponse response) {
        logger.info("selectPaidApplicationSub start");
        String result = "00010";
        String message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        PaymentOrder paymentOrder = new PaymentOrder();
        PaymentOrderMode paymentOrderMode = new PaymentOrderMode();
        List<PaymentOrderSub> paymentOrderSubs = new ArrayList<PaymentOrderSub>();
        if (id == null) {
            id = "2";
        }
        PaidApplication paidApplication = paidApplicationService.selectById(id);
        if (paidApplication != null) {
            if ("4".equals(paidApplication.getPaidStatus())) { //审核通过看到财务付款
                paymentOrder.setPaidAppNumber(paidApplication.getPaidAppNumber());
                paymentOrder.setAppAmount(paidApplication.getAppAmount());
                paymentOrder.setProviderCode(paidApplication.getProviderCode());
                paymentOrder.setProviderName(paidApplication.getProviderName());
                if (null != paidApplication.getPayDate()){
                    paymentOrder.setPaidDate(paidApplication.getPayDate());
                }
                if (null != paidApplication.getRemark()) {
                    paymentOrder.setRemark(paidApplication.getRemark());
                }
            } else if ("5".equals(paidApplication.getPaidStatus()) && null != paidApplication.getF_paymentOrderId()) { //付款单明细
                paymentOrder = paymentOrderService.selectById(paidApplication.getF_paymentOrderId());
                paymentOrderSubs = paymentOrderSubService.selectListByFid(paidApplication.getF_paymentOrderId());
            } else {
                result = "00010";
                message = requestContext.getMessage("application.service.fail");
            }
        }
        paymentOrderMode.setPaymentOrder(paymentOrder);
        paymentOrderMode.setPaymentOrderSubs(paymentOrderSubs);
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject(paymentOrderMode);
        logger.info("selectPaymentOrderSub end");
        WebUtil.responseToJson(response, responseInfo);
    }

    /**
     * 添加子项信息
     * 添加付款单主表信息
     * 添加付款单子表信息
     * 合同表实付金额 添加(每一个合同都添加金额,直到实付金额用完)
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("savePaymentOrderSub")
    public void savePaymentOrderSub(@RequestBody PaymentOrderMode paymentOrderMode,
                                    HttpServletRequest request, HttpServletResponse response) {
        logger.info("savePaymentOrderSub start");
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        int insertId = 1;

        String result = "00010";
        String message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        Object object ="1";
        PaidApplication paidApplication = paidApplicationService.selectById(paymentOrderMode.getPaymentOrder().getF_paidId());
        String f_paidApp = paymentOrderMode.getPaymentOrder().getF_paidId();
        String paymentNumber = "";
        if("4".equals(paidApplication.getPaidStatus())) {

        if (paymentOrderMode != null) {
            //组织付款单主表数据
            PaymentOrder paymentOrder = paymentOrderMode.getPaymentOrder();
            if ("".equals(paymentOrder.getId()) || null == paymentOrder.getId()) {  //新增保存
                paymentNumber = paymentOrderService.getPaymentOrderNumber();
                paymentOrder.setPaidNumber(paymentNumber); //付款单号生成
                paymentOrder.setPayOrderStatus("0"); //状态
                paymentOrder.setF_paidId(f_paidApp);
            }

            paymentOrder.setAccountName(sysUser.getAccountName());
            paymentOrder.setF_account(sysUser.getF_account());
            paymentOrder.setPayPerson(sysUser.getUserName());
            //组织子项数据
            List<PaymentOrderSub> paymentOrderSubs = paymentOrderMode.getPaymentOrderSubs();
            for (PaymentOrderSub paymentOrderSub : paymentOrderSubs) {
                paymentOrder.setPaidNumber(paymentNumber);
                paymentOrderSub.setAccountName(sysUser.getAccountName());
                paymentOrderSub.setF_account(sysUser.getF_account());
            }
            insertId = paymentOrderService.savePaymentOrderSubs(paymentOrder, paymentOrderSubs);

        }
        if (insertId != 1) {
            selectPaymentOrderSub(f_paidApp, request, response);
        }
        } else {
            result = "20001";
            message = messageSource.getMessage("application.service.fail",
                    new Object[]{}, Locale.CHINA);
            logger.info("savePaymentOrderSub end");
            responseInfo.setResult(result);
            responseInfo.setMessage(message);
            responseInfo.setObject(object);
            WebUtil.responseToJson(response, responseInfo);
        }

    }

    /**
     * 付款单明细 点击红冲按钮
     * 1,修改付款单表付款金额 被红冲状态 修改红冲相关号
     * 2,新增付款单表 红冲状态, 金额变负数
     * 3,修改付款申请表 实付金额减少 付款申请子项也减少
     * 4,修改合同表实付金额 和申请金额
     *
     * @param id       付款单id
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("updatePaymentOrderSub")
    public void updatePaymentOrderSub(String id,
                                      HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        logger.info("updatePaymentOrderSub start");
        String result = "00010";
        String message = messageSource.getMessage("select.success",
                new Object[]{}, Locale.CHINA);
        Object object ="1";
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        PaymentOrderMode paymentOrderMode = new PaymentOrderMode();
        int updateId = 1;

        List<PaymentOrderSub> paymentOrderSubs = new ArrayList<PaymentOrderSub>();
        if (!"".equals(id) || null != id) {
            PaymentOrder paymentOrder = paymentOrderService.selectById(id);

            PaidApplication paidApplication = paidApplicationService.selectById(paymentOrder.getF_paidId());
            if("5".equals(paidApplication.getPaidStatus())) {
                if ("0".equals(paymentOrder.getPayOrderStatus())) {  //付款单正常状态可以红冲
                    paymentOrder.setPayOrderStatus("1");
                }
                PaymentOrder paymentOrder1 = paymentOrderService.selectById(id);//红冲付款单

                String paymentNumber = paymentOrderService.getPaymentOrderNumber();
                paymentOrder1.setPaidNumber(paymentNumber); //付款单号生成
                paymentOrder1.setPayOrderStatus("2");
                paymentOrder1.setRealAmount(-paymentOrder1.getRealAmount());
                paymentOrder1.setRedNumber(paymentOrder.getPaidNumber());

                paymentOrder.setRedNumber(paymentNumber); //修改付款单红冲相关号
                paidApplication.setRealAmount(Arith.sub(paidApplication.getRealAmount(), paymentOrder.getRealAmount()));
                paidApplication.setPaidStatus("4"); //审核通过状态

                if (null != paidApplication.getRemark()) {
                    String remark = paidApplication.getRemark();
                    paidApplication.setRemark(remark + ";\n原付款单:" + paymentOrder.getPaidNumber() + "被红冲");
                } else {
                    paidApplication.setRemark("原付款单:" + paymentOrder.getPaidNumber() + "被红冲");

                }
                PaidApplicationSub paidApplicationSub = new PaidApplicationSub();
                paidApplicationSub.setF_paidId(paidApplication.getId());

                List<Contract> contracts = new ArrayList<Contract>();
                List<PaidApplicationSub> paidApplicationSubs = paidApplicationSubService.selectList(paidApplicationSub);//付款申请子项
                for (PaidApplicationSub paidApplicationSub1 : paidApplicationSubs) {
                    if (null != paidApplicationSub1.getRemark()) {
                        String remark = paidApplicationSub1.getRemark();
                        paidApplicationSub1.setRemark(remark + ";\n原金额:" + paidApplicationSub1.getPaidAmount() + "被红冲");
                    } else {
                        paidApplicationSub1.setRemark("原金额:" + paidApplicationSub1.getPaidAmount() + "被红冲");

                    }
                    Contract contract = contractService.selectById(paidApplicationSub1.getF_contractId());
                    contract.setAmountApplication(Arith.add(contract.getAmountApplication(), paidApplicationSub1.getAppBalance()));
                    contract.setAmountPaid(Arith.sub(contract.getAmountPaid(), paidApplicationSub1.getPaidAmount()));
                    contracts.add(contract);
                    paidApplicationSub1.setPaidAmount(0.0); //付款金额变0


                }
                updateId = paymentOrderService.saveUpdatePaymentOrderSubs(paymentOrder, paymentOrder1, paidApplication, paidApplicationSubs, contracts);

                paymentOrderMode.setPaymentOrder(paymentOrder);
                paymentOrderMode.setPaymentOrderSubs(paymentOrderSubs);
                object = paymentOrderMode;
            }else {
                result = "20001";
                message = requestContext.getMessage("application.service.fail");
            }

        } else {
            result = "20001";
            message = requestContext.getMessage("application.service.fail");
        }

        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject(object);
        logger.info("updatePaymentOrderSub end");
        WebUtil.responseToJson(response, responseInfo);
    }

}
